﻿using System.Collections.Generic;
using UnityEngine;

namespace Yoing945
{

    public static class CollectionExtensions
    {
        /// <summary>
        /// 随机获得一个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static T RandomElement<T>(this IList<T> list)
        {
            if (list == null || list.Count == 0)
            {
                return default;
            }
            return list[Random.Range(0, list.Count)];
        }

        /// <summary>
        /// 洗牌(打乱集合元素)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public static void Shuffle<T>(this IList<T> list)
        {
            if (list == null || list.Count < 2)
                return;
            for (var i = 0; i < list.Count; ++i)
            {
                var index = Random.Range(0, list.Count - i);
                var indexOther = list.Count - i - 1;
                (list[indexOther], list[index]) = (list[index], list[indexOther]);
            }
        }

        /// <summary>
        /// 随机获得一个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <returns></returns>
        public static T RandomElement<T>(this T[] array)
        {
            if (array == null || array.Length == 0)
            {
                return default;
            }
            return array[Random.Range(0, array.Length)];
        }


        /// <summary>
        /// 洗牌(打乱集合元素)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public static void Shuffle<T>(this T[] array)
        {
            if (array == null || array.Length < 2)
                return;
            for (var i = 0; i < array.Length; ++i)
            {
                var index = Random.Range(0, array.Length - i);
                var indexOther = array.Length - i - 1;
                (array[indexOther], array[index]) = (array[index], array[indexOther]);
            }
        }


        /// <summary>
        /// 获取极值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="comparison"></param>
        /// <returns></returns>
        public static T GetExtremum<T>(this IList<T> list, System.Comparison<T> comparison)
        {
            T extremum = list[0];
            for (var i = 1; i < list.Count; ++i)
            {
                var val = list[i];
                if (comparison(extremum, val) < 0)
                {
                    extremum = val;
                }
            }
            return extremum;
        }
    }
}

